package com.glaway.car.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.glaway.car.Service.RecordService;
import com.glaway.car.context.BaseContext;
import com.glaway.car.dto.RecordDTO;
import com.glaway.car.dto.UserDTO;
import com.glaway.car.entity.Record;
import com.glaway.car.mapper.RecordMapper;
import com.glaway.car.result.PageResult;
import com.glaway.car.utils.AesUtils;
import com.glaway.car.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    RecordMapper recordMapper;
    private static final String AES_KEY = "key";

    @Override
    public PageResult<Record> queryRecord(RecordDTO recordDTO) {

        Integer permission = BaseContext.getCurrentAdmin().getPermission();
        // 1. 分页查询（返回包含加密手机号的数据）
        PageHelper.startPage(recordDTO.getPage(), recordDTO.getPageSize(),false);
        List<Record> recordList = recordMapper.queryRecord(recordDTO);
        Page<Record> p = (Page<Record>) recordList;

        // 2. 解密处理
        List<Record> decryptedRecords = p.getResult().stream()
                .map(recordAes -> {
                    Record record = new Record();
                    // 2.1. 拷贝基础字段
                    BeanUtils.copyProperties(recordAes, record);
                    // 2.2. 处理手机号解密
                    try {
                        String decryptedPhoneNumber = AesUtils.decrypt(recordAes.getAesPhoneNumber(), AES_KEY);
                        // 根据权限决定显示方式
                        if (permission == 1) {
                            record.setPhoneNumber(decryptedPhoneNumber); // 管理员显示完整号码
                        } else {
                            record.setPhoneNumber(maskPhoneNumber(decryptedPhoneNumber)); // 其他人员脱敏
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                    return record;
                })
                .collect(Collectors.toList());

        return new PageResult<>(p.getTotal(), decryptedRecords);
    }

    @Override
    public PageResult<UserVO> queryUser(UserDTO userDTO) {

        Integer permission = BaseContext.getCurrentAdmin().getPermission();
        PageHelper.startPage(userDTO.getPage(), userDTO.getPageSize());
        List<UserVO> userList = recordMapper.queryUserDesc(userDTO);
        Page<UserVO> p = (Page<UserVO>) userList;

        List<UserVO> resultUsers = p.getResult().stream()
                .map(user -> {
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(user, userVO);

                    try {
                        String decryptedPhoneNumber = AesUtils.decrypt(user.getAesPhoneNumber(), AES_KEY);
                        if (permission == 1) {
                            userVO.setPhoneNumber(decryptedPhoneNumber);
                        } else {
                            userVO.setPhoneNumber(maskPhoneNumber(decryptedPhoneNumber));
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                    return userVO;
                })
                .collect(Collectors.toList());

        // 3. 返回分页结果
        return new PageResult<>(p.getTotal(), resultUsers);
    }

    @Override
    public ReportVO queryDayReport(LocalDate localDate) {
        List<String> timeList = new ArrayList<>();
        List<String> countList = new ArrayList<>();

        List<ReportVOTemp> countMapList = recordMapper.queryCount(localDate, localDate.plusDays(1));

        // 遍历结果列表，将 time 和 count 分别添加到对应的列表中
        if (countMapList != null && !countMapList.isEmpty()) {
            for (ReportVOTemp item : countMapList) {
                timeList.add(item.getTime());
                countList.add(item.getCount());
            }
        }

        return new ReportVO(timeList, countList);
    }

    /**
     * 手机号脱敏（格式：139****2350）
     */
    private String maskPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.length() != 11) {
            return phoneNumber; // 非11位手机号原样返回
        }
        return phoneNumber.substring(0, 3) + "****" + phoneNumber.substring(7);
    }

}